package org.momo.rpc.loadbalance;

import lombok.extern.slf4j.Slf4j;
import org.momo.rpc.constant.LoadBalanceKey;
import org.momo.rpc.exception.RpcReferenceConfigException;
import org.momo.rpc.loadbalance.impl.ConsistentHashLoadBalancer;
import org.momo.rpc.loadbalance.impl.PollingLoadBalancer;
import org.momo.rpc.loadbalance.impl.RandomLoadBalancer;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


@Slf4j
public class LoadBalanceProvider {

    private static final Map<String, LoadBalancer> loadBalancerMap = new ConcurrentHashMap<>();

    public static void initLoadBalancer(String loadBalanceName, LoadBalanceKey loadBalanceKey) {
        LoadBalancer loadBalancer = null;
        switch (loadBalanceKey) {
            case RANDOM:
                loadBalancer = new RandomLoadBalancer();
                break;
            case POLLING:
                loadBalancer = new PollingLoadBalancer();
                break;
            case CONSISTENT_HASH:
                loadBalancer = new ConsistentHashLoadBalancer();
                break;
            default:
                log.error("loadBalanceKey {} is not exist", loadBalanceKey.getKey());
                return;
        }

        if(loadBalancerMap.containsKey(loadBalanceName)) {
            log.error("LoadBalance already exists, the loadbalanceName is {}", loadBalanceName);
            return;
        }
        loadBalancerMap.put(loadBalanceName, loadBalancer);
    }

    public static LoadBalancer getLoadBalancer(String loadBalanceName) {
        return loadBalancerMap.get(loadBalanceName);
    }

}
